package com.bantang.controller;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/queue")
@Slf4j
@Profile({"dev","local"})
public class QueueController {

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;


    @GetMapping("/add")
    public void add(String name){
        CompletableFuture.runAsync(
                ()->{
                    log.info("执行任务：+"+name+"处理当前任务线程："+Thread.currentThread().getName());
                    try {
                        Thread.sleep(600000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                },threadPoolExecutor
        );
    }
    @GetMapping("/get")
    public String get(){
        Map<String,Object> map = new HashMap<>();

        //获取线程池队列长度
        int size = threadPoolExecutor.getQueue().size();

        map.put("队列长度",size);

        //获取线程池已接受的任务总数
        long count = threadPoolExecutor.getTaskCount();
        map.put("已接受任务总数",count);

        long countC = threadPoolExecutor.getCompletedTaskCount();
        map.put("已完成的任务数",countC);

        long activeCount = threadPoolExecutor.getActiveCount();
        map.put("正在执行的线程数",activeCount);

        return JSONUtil.toJsonStr(map);

    }

}
